//
//  GestureLoginVC.m
//  IDCardManager
//
//  Created by 金牛 on 2017/8/26.
//  Copyright © 2017年 zou. All rights reserved.
//

#import "GestureLoginVC.h"
#import "PCCircleView.h"
#import "PCLockLabel.h"
#import "PCCircleViewConst.h"
#import "PCCircleInfoView.h"
#import "NewTabbarVC.h"
#import "PCCircle.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "FingerVerifyVC.h"
#import <AudioToolbox/AudioToolbox.h>
@interface GestureLoginVC ()<CircleViewDelegate>
{
    PCLockLabel * _msgLab ;
    PCCircleInfoView * _infoView;
    UIImageView * _bgView;
    UILabel * _navTitleLab;
    UILabel *_label;
}
@end

@implementation GestureLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.gestureType ==1) {
        [self createInputGestureView];
        _label = [UILabel labelWithTitle:@"请输入手势密码" color:[UIColor blackColor] fontSize:16 alignment:NSTextAlignmentCenter];
        [self.view addSubview:_label];
        _label.sd_layout.topSpaceToView(self.view, 190).leftSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).heightIs(20);
    }else{
        [self createSetGestureView];
    }
}
-(void)createInputGestureView{
    _navTitleLab.text = @"输入解锁手势";
    _bgView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    _bgView.userInteractionEnabled = YES;
    [self.view addSubview:_bgView];
    _bgView.image = Image(@"gesture_login");
    PCCircleView *lockView = [[PCCircleView alloc]initWithType:CircleViewTypeLogin clip:YES arrow:NO withCenterFloat:60];
    lockView.delegate = self;
    [_bgView addSubview:lockView];
    
    _msgLab = [[PCLockLabel alloc] init];
    _msgLab.frame = CGRectMake(0, 0, IPHONE_WIDTH, 14);
    _msgLab.center = CGPointMake(IPHONE_WIDTH/2, CGRectGetMinY(lockView.frame) - 30);
    [_bgView addSubview:_msgLab];
}
-(void)createSetGestureView{
    _navTitleLab.text = @"设置解锁手势";
    self.view.backgroundColor = [UIColor colorWithHue:0.61 saturation:0.01 brightness:0.96 alpha:1];
    PCCircleView *lockView = [[PCCircleView alloc]initWithType:CircleViewTypeSetting clip:YES arrow:NO withCenterFloat:0];
    lockView.delegate = self;
    [self.view addSubview:lockView];
    
    [lockView setType:CircleViewTypeSetting];
    _msgLab = [[PCLockLabel alloc] init];
    _msgLab.frame = CGRectMake(0, 0, IPHONE_WIDTH, 14);
    _msgLab.center = CGPointMake(IPHONE_WIDTH/2, CGRectGetMinY(lockView.frame) - 30);
    
    [self.view addSubview:_msgLab];
    [_msgLab showNormalMsg:@"绘制解锁图案"];
    _infoView = [[PCCircleInfoView alloc] init];
    _infoView.frame = CGRectMake(0, 0, CircleRadius * 2 * 0.6, CircleRadius * 2 * 0.6);
    _infoView.center = CGPointMake(kScreenW/2, CGRectGetMinY(_msgLab.frame) - CGRectGetHeight(_infoView.frame)/2 - 10);
    [self.view addSubview:_infoView];
    
}
- (void)circleView:(PCCircleView *)view type:(CircleViewType)type connectCirclesLessThanNeedWithGesture:(NSString *)gesture{
    NSString *gestureOne = [PCCircleViewConst getGestureWithKey:gestureOneSaveKey];
    // 看是否存在第一个密码
    if ([gestureOne length]) {
        VLog(@"提示再次绘制之前绘制的第一个手势密码");
        [_msgLab showNormalMsg:@"请重复正确手势"];
    } else {
        VLog(@"密码长度不合法%@", gesture);
        [_msgLab showWarnMsg:@"请设置至少四个连线"];
    }
}
- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteSetFirstGesture:(NSString *)gesture{
    VLog(@"获得第一个手势密码%@", gesture);
    // infoView展示对应选中的圆
    [_msgLab showNormalMsg:@"请重复手势"];
    [self infoViewSelectedSubviewsSameAsCircleView:view];
    
}

- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteSetSecondGesture:(NSString *)gesture result:(BOOL)equal{
    VLog(@"获得第二个手势密码%@",gesture);
    if (equal) {
        VLog(@"两次手势匹配！可以进行本地化保存了");
        NSUserDefaults * def = [NSUserDefaults standardUserDefaults];
        [def setObject:gesture forKey:@"gesturelock"];
        [self gotoTabBarView];
    } else {
        [_msgLab showWarnMsg:@"两次手势不匹配！"];
    }
}
-(void)showAlertView{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否启用指纹解锁" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSUserDefaults * def = [NSUserDefaults standardUserDefaults];
        //先判断指纹能否用
        LAContext* context = [[LAContext alloc] init];
        NSError* error = nil;
        //首先使用canEvaluatePolicy 判断设备支持状态
        if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
            [def setObject:@"YES" forKey:@"fingerstate"];
            dispatch_async(dispatch_get_main_queue(), ^{
                FingerVerifyVC * finger = [FingerVerifyVC new];
                [UIApplication sharedApplication].keyWindow.rootViewController = finger;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [Mytools warnText:@"设备不支持Touch ID" status:Error];
                [self gotoTabBarView];
            });
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self gotoTabBarView];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}
-(void)gotoTabBarView{
    [UIApplication sharedApplication].keyWindow.rootViewController = [[NewTabbarVC alloc] init];
}
#pragma mark - circleView - delegate - login or verify gesture
- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteLoginGesture:(NSString *)gesture result:(BOOL)equal{
    // 此时的type有两种情况 Login or verify
    if (type == CircleViewTypeLogin) {
        if (equal) {
            VLog(@"登陆成功！");
            NSUserDefaults * def = [NSUserDefaults standardUserDefaults];
            NSString * fingerStr = [def objectForKey:@"fingerstate"];
            if ([fingerStr isEqualToString:@"YES"]) {
                //先判断指纹能否用
                LAContext* context = [[LAContext alloc] init];
                NSError* error = nil;
                //首先使用canEvaluatePolicy 判断设备支持状态
                if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
                    NSString * fingerStr = [def objectForKey:@"fingerstate"];
                    if ([fingerStr isEqualToString:@"YES"]) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            FingerVerifyVC * finger = [FingerVerifyVC new];
                            [UIApplication sharedApplication].keyWindow.rootViewController = finger;
                        });
                        
                    }else if([fingerStr isEqualToString:@"NO"]){
                        [self gotoTabBarView];
                    }
                }else{
                    [self gotoTabBarView];
                }
            }else{
                [self gotoTabBarView];
            }
            
        } else {
            [self shakeAnimationForView:_label];
            _label.text = @"密码错误";
            _label.textColor = [UIColor redColor];
        }
    } else if (type == CircleViewTypeVerify) {
        
        if (equal) {
            VLog(@"验证成功，跳转到设置手势界面");
            
        } else {
            VLog(@"原手势密码输入错误！");
            
        }
    }
}
- (void)shakeAnimationForView:(UIView *) view{
    CALayer *viewLayer = view.layer;
    CGPoint position = viewLayer.position;
    CGPoint x = CGPointMake(position.x + 10, position.y);
    CGPoint y = CGPointMake(position.x - 10, position.y);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    [animation setAutoreverses:YES];
    [animation setDuration:.06];
    [animation setRepeatCount:3];
    [viewLayer addAnimation:animation forKey:nil];
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
#pragma mark - 让infoView对应按钮选中
- (void)infoViewSelectedSubviewsSameAsCircleView:(PCCircleView *)circleView {
    for (PCCircle *circle in circleView.subviews) {
        
        if (circle.circleState == CircleStateSelected || circle.circleState == CircleStateLastOneSelected) {
            
            for (PCCircle *infoCircle in _infoView.subviews) {
                if (infoCircle.tag == circle.tag) {
                    [infoCircle setCircleState:CircleStateSelected];
                }
            }
        }
    }
}

@end
